package com.kaibes.module.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.web.api.ApiLinkData;
import com.kaibes.web.api.ApiLinkService;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/apis")
public class ConllectApi {
    
    @Value("${spring.application.name}")
    private String appName;
    @Autowired
    private ApiLinkService apiLinkService;
    private Map<String, List<ApiLinkData>> apiMap = new HashMap<>();
    
    @PostMapping
    public void init() {
        List<ApiLinkData> apiList = apiLinkService.listApi();
        apiMap.put(appName, apiList);
    }
    
    @GetMapping
    public ResponseEntity<Map<String, List<ApiLinkData>>> all() {
        return ResponseFactory.get(apiMap, "获取API列表成功", "获取API列表失败");
    }
    
    @PostMapping("/{service}")
    public void post(@PathVariable String service, @RequestBody List<ApiLinkData> data) {
        apiMap.put(service, data);
    }
    
    @DeleteMapping("/{service}")
    public void delete(@PathVariable String service) {
        apiMap.remove(service);
    }
    
    @GetMapping("/{service}")
    public ResponseEntity<List<ApiLinkData>> get(@PathVariable String service) {
        return ResponseFactory.get(apiMap.get(service), "获取API列表成功", "获取API列表失败");
    }
    
    @GetMapping("/{service}/{uri}")
    public ResponseEntity<List<ApiLinkData>> get(@PathVariable String service, @PathVariable String uri) {
        List<ApiLinkData> dataList = apiMap.get(service);
        List<ApiLinkData> result = new ArrayList<>();
        for (ApiLinkData apiLinkData : dataList) {
            List<String> patternList = apiLinkData.getPatternList();
            for (String pattern : patternList) {
                if (pattern.startsWith("/"+uri)) {
                    result.add(apiLinkData);
                    break;
                }
            }
        }
        return ResponseFactory.get(result, "获取API列表成功", "获取API列表失败");
    }
    
}
